package com.ity.teamanagement.exception;

import com.ity.teamanagement.code.CommonCode;
import com.ity.teamanagement.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author coderFu
 * @create 2021/5/23
 * RestControllerAdvice对Controller进行增强，可以全局捕获spring mvc 抛的异常
 * ExceptionHandler（value= Exception.class) 捕获指定的异常
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class UniformResponseHandler<T> {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        //从异常中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getFieldErrors().get(0);
        log.error("Code:400 参数非法:{}", objectError.getDefaultMessage());
        return new Result<>(CommonCode.PARAMETER_ERROR,objectError.getDefaultMessage());
    }

    @ExceptionHandler(ApiException.class)
    public Result ApiException(ApiException e){
        log.error("Code:{} - ApiException:{}", e.getResult().getCode(), e.getResult().getMessage());
        return e.getResult();
    }


}
